package com.south.base.test.arithmetic.tree;

import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Administrator
 * @date 2020/7/22 14:43
 */
public class NTree {
    /**
     * N叉树的前序遍历
     * 给定一个 N 叉树，返回其节点值的前序遍历。
     */
    @Test
    public void preOrder() {
        List<Node> nodes = Arrays.asList(new Node(5), new Node(6));
        nodes = Arrays.asList(new Node(3, nodes), new Node(2), new Node(4));
        Node root = new Node(1, nodes);
        Assert.assertEquals(preOrder(root), preOrder2(root));
        Assert.assertEquals(postOrder(root), postOrder2(root));
    }

    public List<Integer> preOrder2(Node root) {
        List<Integer> res = new ArrayList<>();
        LinkedList<Node> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            Node node = queue.pollLast();
            if (node == null) {
                continue;
            }
            res.add(node.val);
            if (node.children == null) {
                continue;
            }
            for (int i = node.children.size() - 1; i >= 0; i--) {
                queue.add(node.children.get(i));
            }
        }
        return res;
    }

    public List<Integer> preOrder(Node root) {
        List<Integer> res = new ArrayList<>();
        preOrder(root, res);
        return res;
    }

    public void preOrder(Node root, List<Integer> list) {
        if (root == null) {
            return;
        }
        list.add(root.val);
        if (root.children == null) {
            return;
        }
        for (int i = 0; i < root.children.size(); i++) {
            preOrder(root.children.get(i), list);
        }
    }

    /**
     * N叉树的后序遍历
     *
     * @param root
     * @return
     */
    public List<Integer> postOrder2(Node root) {
        List<Integer> res = new ArrayList<>();
        postOrder2(root, res);
        return res;
    }

    public void postOrder2(Node root, List<Integer> list) {
        if (root == null) {
            return;
        }
        if (root.children != null) {
            for (int i = 0; i < root.children.size(); i++) {
                postOrder2(root.children.get(i), list);
            }
        }
        list.add(root.val);
    }

    public List<Integer> postOrder(Node root) {
        LinkedList<Node> stack = new LinkedList<>();
        LinkedList<Integer> output = new LinkedList<>();
        if (root == null) {
            return output;
        }

        stack.add(root);
        while (!stack.isEmpty()) {
            Node node = stack.pollLast();
            output.addFirst(node.val);
            if (node.children == null) {
                continue;
            }
            for (Node item : node.children) {
                if (item != null) {
                    stack.add(item);
                }
            }
        }
        return output;
    }

}
